package com.codi.api.interceptor;

import com.codi.api.security.UserUtil;
import com.codi.base.util.StringUtil;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.resultModel.ValidateTokenResult;
import com.codi.bus.core.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 尝试探测session
 *
 * @author shi.pengyan
 * @version 1.0 2017-10-20 14:42
 * @since 1.0
 */
@Slf4j
public class DetectSessionInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token    = request.getHeader(GlobalConstant.HEADER_AUTH_TOKEN);
        String deviceId = request.getHeader(GlobalConstant.HEADER_APP_DEVICE);

        if (StringUtil.isNotEmpty(token) && StringUtil.isNotEmpty(deviceId)) {
            // 验证token
            ValidateTokenResult validateTokenResult = userService.validateToken(token, deviceId);
            if (validateTokenResult.getSuccess()) {
                UserUtil.setUserId(validateTokenResult.getUserId());
            }
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtil.clear();
    }
}
